import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mahjong/entity/Restful.dart';
import 'package:mahjong/entity/UserEntityInfo.dart';
import 'package:mahjong/util/CustomerDialog.dart';
import 'package:mahjong/util/DictionaryConst.dart';
import 'package:mahjong/util/Http.dart';
import 'package:mahjong/widget/CommonAlterDialog.dart';
import 'package:mahjong/widget/CropImageRoute.dart';
import 'package:mahjong/widget/CustomDialog.dart';
import 'package:provider/provider.dart';
import 'package:mahjong/widget/CommonBottomSheet.dart';

typedef _CallBack = void Function(String roomCode);

class UserInfoDialog extends StatefulWidget {
  final String title, description;
  final Image image;
  final _CallBack callback;

  UserInfoDialog({
    @required this.title,
    @required this.description,
    this.callback,
    this.image,
  });
  @override
  _UserInfoDialogState createState() => _UserInfoDialogState();
}

class _UserInfoDialogState extends State<UserInfoDialog> {
  double dialogHeight, dialogWidth;
  final ImagePicker _picker = ImagePicker();
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    dialogHeight = ScreenUtil().setHeight(200);
    dialogWidth = 500.sp;
    return CommonAlterDialog(
        height: dialogHeight,
        width: dialogWidth,
        backgroundColor: Colors.white,
        child: Consumer(builder:
            (BuildContext buildContext, UserEntityInfo provider, Widget child) {
          return Container(
              padding: EdgeInsets.all(ScreenUtil().setHeight(20)),
              width: dialogWidth,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        InkWell(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Container(
                              width: dialogHeight / 3,
                              height: dialogHeight / 3,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                      color: Colors.black12,
                                      width: dialogHeight / 40)),
                              child: provider.sysUser.portraitUrl == null
                                  ? Image.asset(
                                      "images/mahjong/user/header/common_header.png",
                                      fit: BoxFit.cover,
                                    )
                                  : CachedNetworkImage(
                                      width: double.infinity,
                                      height: double.infinity,
                                      fit: BoxFit.cover,
                                      placeholder: (context, url) =>
                                          CircularProgressIndicator(),
                                      errorWidget: (context, url, error) =>
                                          Icon(Icons.error),
                                      imageUrl: DictionaryConst.filePath +
                                          provider.sysUser.portraitUrl,
                                    ),
                            ),
                          ),
                          onTap: () async {
                            showDialog(
                                barrierDismissible:
                                    true, //是否点击空白区域关闭对话框,默认为true，可以关闭
                                context: context,
                                builder: (BuildContext context) {
                                  var list = [];
                                  list.add('更换头像');
                                  return CommonBottomSheet(
                                    list: list,
                                    onItemClickListener: (index) async {
                                      final PickedFile file =
                                          await _picker.getImage(
                                        source: ImageSource.gallery,
                                      );
                                      File cropFile =
                                          await _cropImage(file.path);

                                      Http.getInstance().request<Restful>(
                                          DictionaryConst.uploadFile +
                                              "head_sculpture",
                                          type: RequestEnum.POST,
                                          contentType: ContentType.json,
                                          responseType: ResponseType.json,
                                          showLoading: true,
                                          loadingMsg: "修改用户信息中...",
                                          data: FormData.fromMap({
                                            "file":
                                                await MultipartFile.fromFile(
                                              cropFile.path,
                                              filename: "xxx.jpg",
                                            ),
                                          }), success: (data) {
                                        SysUser userInfo = new SysUser();
                                        userInfo.portraitUrl =
                                            "head_sculpture/" + data.body;
                                        Http.getInstance().request<Restful>(
                                            DictionaryConst.userUpdate,
                                            type: RequestEnum.POST,
                                            contentType: ContentType.json,
                                            showLoading: true,
                                            loadingMsg: "修改用户信息中...",
                                            data: userInfo.toJson(),
                                            success: (data) {
                                          Provider.of<UserEntityInfo>(context,
                                                  listen: false)
                                              .updateUserInfo(
                                                  imagePath:
                                                      userInfo.portraitUrl);
                                          Navigator.of(context).pop();
                                        }, error: (data) {
                                          CustomerDialog.showText(data.msg);
                                        });
                                      }, error: (data) {
                                        CustomerDialog.showText(data.msg);
                                        setState(() {});
                                      });
                                    },
                                  );
                                });
                          },
                        ),
                        Text(provider.sysUser.username,
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 18.sp,
                            )),
                        Text("ID:" + provider.sysUser.id.toString(),
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 18.sp,
                            ))
                      ]),
                  SizedBox(
                    width: 1,
                    height: dialogHeight,
                    child: DecoratedBox(
                      decoration: BoxDecoration(
                          border: Border.all(
                              color: Colors.orange[100], width: 1.0)),
                    ),
                  ),
                  Column(
                    children: [
                      buildHistoryItem("总局数:", "200"),
                      buildHistoryItem("放炮次数:", "100"),
                      buildHistoryItem("胡牌次数:", "100"),
                      buildHistoryItem("胜率:", "50%")
                    ],
                  )
                ],
              ));
        }));
  }

  Future<File> _cropImage(String path) async {
    File croppedFile = await ImageCropper.cropImage(
        sourcePath: path,
        aspectRatioPresets: Platform.isAndroid
            ? [
                CropAspectRatioPreset.square,
                CropAspectRatioPreset.ratio3x2,
                CropAspectRatioPreset.original,
                CropAspectRatioPreset.ratio4x3,
                CropAspectRatioPreset.ratio16x9
              ]
            : [
                CropAspectRatioPreset.original,
                CropAspectRatioPreset.square,
                CropAspectRatioPreset.ratio3x2,
                CropAspectRatioPreset.ratio4x3,
                CropAspectRatioPreset.ratio5x3,
                CropAspectRatioPreset.ratio5x4,
                CropAspectRatioPreset.ratio7x5,
                CropAspectRatioPreset.ratio16x9
              ],
        androidUiSettings: AndroidUiSettings(
            toolbarTitle: 'Cropper',
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: false),
        iosUiSettings: IOSUiSettings(
          title: 'Cropper',
        ));
    return croppedFile;
  }

  Container buildHistoryItem(String text, String value) {
    return Container(
      height: dialogHeight / 10,
      width: dialogWidth / 4,
      margin: EdgeInsets.only(bottom: dialogHeight / 20),
      decoration: BoxDecoration(
        border: Border(
            bottom:
                BorderSide(color: Colors.orange.withOpacity(0.5), width: 1)),
      ),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(text,
              style: TextStyle(
                color: Colors.black,
                fontSize: 16.sp,
              )),
          Text(value,
              style: TextStyle(
                color: Colors.black,
                fontSize: 16.sp,
              ))
        ],
      ),
    );
  }
}
